/**
 * 将rpx转换为px
 * @param {number} rpx - 待转换的rpx值
 * @returns {number} 转换后的px值
 */
function rpxToPx(rpx: number) {
  // 获取设备信息（屏幕宽度，单位px）
  const systemInfo = wx.getSystemInfoSync();
  const screenWidth = systemInfo.screenWidth;

  // 计算px值（四舍五入保留整数）
  return Math.round(rpx * (screenWidth / 750));
}

/**
 * 将px转换为rpx
 * @param {number} px - 待转换的px值
 * @returns {number} 转换后的rpx值
 */
function pxToRpx(px: number) {
  const systemInfo = wx.getSystemInfoSync();
  const screenWidth = systemInfo.screenWidth;

  return Math.round(px * (750 / screenWidth));
}

function throttle(fn: AnyFunction, interval: number) {
  let timer: number | null = null;
  return function (this: any, ...args: any[]) {
    console.log("throttle", args);
    if (!timer) {
      // 无定时器时才创建
      timer = setTimeout(() => {
        fn.apply(this, args);
        timer = null; // 执行后清空定时器
        console.log("throttle run", args);
      }, interval);
    }
  };
}

function debounce(fn: AnyFunction, delay: number) {
  let timer: number | null = null;
  return function (this: any, ...args: any[]) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

module.exports = {
  rpxToPx,
  pxToRpx,
  throttle,
  debounce,
};
